package ee.roosideSoda.backend.model.dao.postgresqlimplementations;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import ee.roosideSoda.backend.database.ConnectionManager;
import ee.roosideSoda.backend.model.dao.YldkysimusDAO;
import ee.roosideSoda.backend.model.data.Yldkysimus;

public class YldkysimusDAOPostgresqlImpl implements YldkysimusDAO
{
	Logger logger = Logger.getLogger(YldkysimusDAOPostgresqlImpl.class);
	Connection dbConnection;
	String sql;
	PreparedStatement preparedStatement;
	Statement statement;
	ResultSet resultSet;
	private final int WARNING_NO_ROWS_AFFECTED = 0;
	private int rowsAffected;
	
	public YldkysimusDAOPostgresqlImpl(Connection dbConnection)
	{
		this.dbConnection = dbConnection;
	}

	@Override
	public int sisestaYldkysimus(Yldkysimus yldkysimus)
	{
		resultSet = null;
		rowsAffected = WARNING_NO_ROWS_AFFECTED;
		sql = "INSERT INTO Yldkysimused (teema, onVastatud) " + 
				"VALUES (?, ?);";
		
		try 
		{
			preparedStatement = dbConnection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
			
			preparedStatement.setString	(1, yldkysimus.getTeema());
			preparedStatement.setBoolean(2, yldkysimus.getOnVastatud());
			
			logger.info(preparedStatement.toString());
			rowsAffected = preparedStatement.executeUpdate();
			
			if (rowsAffected == 1)
			{
				resultSet = preparedStatement.getGeneratedKeys();
				resultSet.next(); //answer consist only 1 row, so move the cursor just once to start to process the result
				int newId = resultSet.getInt(1); // 1, because identifiers are held in the first column 
				yldkysimus.setYldkysimusID(newId);
				return rowsAffected;
			}
			else
			{
				System.out.println("No rows affected!");
				logger.info("Unsuccessful insertion to a database: " + preparedStatement.toString());
				return WARNING_NO_ROWS_AFFECTED;
			}
		}
		catch (Exception e) 
		{
			e.printStackTrace();
			return WARNING_NO_ROWS_AFFECTED;
		}
		finally
		{
			ConnectionManager.getInstance().closeStatement(preparedStatement);
			ConnectionManager.getInstance().closeResultSet(resultSet);
		}
	}

	@Override
	public Yldkysimus saaYldkysimusIDJargi(int yldkysimuseID)
	{
		resultSet = null;
		Yldkysimus yldkysimuseAndmedAndmebaasist = null;
		sql = "SELECT * FROM Yldkysimused WHERE yldkysimusID = ?";
		
		try 
		{
			preparedStatement = dbConnection.prepareStatement(
						sql,
						ResultSet.TYPE_SCROLL_INSENSITIVE,
						ResultSet.CONCUR_READ_ONLY
					);
			//filling the placeholders 
			preparedStatement.setInt(1, yldkysimuseID);
			logger.info(preparedStatement.toString());
			resultSet = preparedStatement.executeQuery();
			//place the cursor at the beginning of a received data set (so it can start to read and process data)
			resultSet.beforeFirst();
			
			if (resultSet.next())
			{
				//setObject() is used, when column or field value in java, can also be null.
				yldkysimuseAndmedAndmebaasist = new Yldkysimus();
				yldkysimuseAndmedAndmebaasist.setYldkysimusID(resultSet.getInt("yldkysimusID"));
				yldkysimuseAndmedAndmebaasist.setTeema(resultSet.getString("teema"));
				yldkysimuseAndmedAndmebaasist.setOnVastatud(resultSet.getBoolean("onVastatud"));
			}
		}
		catch (SQLException e) 
		{
			logger.error(e.getMessage());
		}
		finally
		{
			ConnectionManager.getInstance().closeStatement(preparedStatement);
			ConnectionManager.getInstance().closeResultSet(resultSet);
		}
		
		return yldkysimuseAndmedAndmebaasist;
	}

	@Override
	public int margiYldkysimusVastatuks(int yldkysimuseID) 
	{
		resultSet = null;
		rowsAffected = WARNING_NO_ROWS_AFFECTED;
		sql = "UPDATE Yldkysimused " + 
				"SET onVastatud = ? " + 
				"WHERE yldkysimusID = ?;"; 
		
		try 
		{
			preparedStatement = dbConnection.prepareStatement(sql);
			
			preparedStatement.setBoolean(1, true);
			preparedStatement.setInt	(2, yldkysimuseID);
			
			rowsAffected = preparedStatement.executeUpdate();
			
			if (rowsAffected == 1)
			{
				logger.info("Update sucessful: " + preparedStatement.toString());
				return rowsAffected;
			}
			else
			{
				logger.error("Update was unsuccesful: " + preparedStatement.toString());
				return WARNING_NO_ROWS_AFFECTED;
			}
		}
		catch (SQLException e) 
		{
			logger.error(e.getMessage());
			return WARNING_NO_ROWS_AFFECTED;		
		}
		finally
		{
			ConnectionManager.getInstance().closeStatement(preparedStatement);
			ConnectionManager.getInstance().closeResultSet(resultSet);
		}
	}

	@Override
	public List<Yldkysimus> saaKoikideVastamataYldkysimusteList()
	{
		resultSet = null;
		Yldkysimus yldkysimuseAndmedAndmebaasist = null;
		List<Yldkysimus> koikideYldkysimusteList = new ArrayList<Yldkysimus>();
		sql = "SELECT * FROM Yldkysimused WHERE onVastatud = false";
		
		try 
		{
			preparedStatement = dbConnection.prepareStatement(
						sql,
						ResultSet.TYPE_SCROLL_INSENSITIVE,
						ResultSet.CONCUR_READ_ONLY
					);
			//filling the placeholders 
			logger.info(preparedStatement.toString());
			resultSet = preparedStatement.executeQuery();
			//place the cursor at the beginning of a received data set (so it can start to read and process data)
			resultSet.beforeFirst();
			
			while (resultSet.next())
			{
				//setObject() is used, when column or field value in java, can also be null.
				yldkysimuseAndmedAndmebaasist = new Yldkysimus();
				yldkysimuseAndmedAndmebaasist.setYldkysimusID(resultSet.getInt("yldkysimusID"));
				yldkysimuseAndmedAndmebaasist.setTeema(resultSet.getString("teema"));
				yldkysimuseAndmedAndmebaasist.setOnVastatud(resultSet.getBoolean("onVastatud"));
			
				koikideYldkysimusteList.add(yldkysimuseAndmedAndmebaasist);
			}
		}
		catch (SQLException e) 
		{
			logger.error(e.getMessage());
		}
		finally
		{
			ConnectionManager.getInstance().closeStatement(preparedStatement);
			ConnectionManager.getInstance().closeResultSet(resultSet);
		}
		
		return koikideYldkysimusteList;
	}
	
	@Override
	public List<Yldkysimus> saaKoikideVastamataYldkysimusteListPealeEtteantudID(
			int yldkysimusIDMidaVastusesseEiTaheta) 
	{
		resultSet = null;
		Yldkysimus yldkysimuseAndmedAndmebaasist = null;
		List<Yldkysimus> koikideYldkysimusteList = new ArrayList<Yldkysimus>();
		sql = "SELECT * FROM Yldkysimused WHERE yldkysimusID != ? AND onVastatud = false";
		
		try 
		{
			preparedStatement = dbConnection.prepareStatement(
						sql,
						ResultSet.TYPE_SCROLL_INSENSITIVE,
						ResultSet.CONCUR_READ_ONLY
					);
			//filling the placeholders 
			preparedStatement.setInt(1, yldkysimusIDMidaVastusesseEiTaheta);
			logger.info(preparedStatement.toString());
			resultSet = preparedStatement.executeQuery();
			//place the cursor at the beginning of a received data set (so it can start to read and process data)
			resultSet.beforeFirst();
			
			while (resultSet.next())
			{
				//setObject() is used, when column or field value in java, can also be null.
				yldkysimuseAndmedAndmebaasist = new Yldkysimus();
				yldkysimuseAndmedAndmebaasist.setYldkysimusID(resultSet.getInt("yldkysimusID"));
				yldkysimuseAndmedAndmebaasist.setTeema(resultSet.getString("teema"));
				yldkysimuseAndmedAndmebaasist.setOnVastatud(resultSet.getBoolean("onVastatud"));
			
				koikideYldkysimusteList.add(yldkysimuseAndmedAndmebaasist);
			}
		}
		catch (SQLException e) 
		{
			logger.error(e.getMessage());
		}
		finally
		{
			ConnectionManager.getInstance().closeStatement(preparedStatement);
			ConnectionManager.getInstance().closeResultSet(resultSet);
		}
		
		return koikideYldkysimusteList;
	}
}
